# -*- encoding: utf-8 -*-
"""
File Name: zabbix_agent_manager
Description:
Author : 'lirui'
date: 2024/1/8
Contact: marjey_lee@163.com
Change Activity:
2024/1/8:
"""
from collections import defaultdict

import ll
from modules.zabbix_utils.utils.zabbix_client import ZabbixClient
from projects.generation.create_zabbix_device_snmp_monitor.config.config import ZABBIX_SERVER_USERNAME, ZABBIX_SERVER_PASSWORD


class ZabbixClientManager:
    def __init__(self, config):
        self.config = config
        self.port_client_mapping = self._load_id_clients_mapping()

    def logout(self):
        for _, cs in self.port_client_mapping.items():
            for c in cs:
                c.logout()

    def _load_id_clients_mapping(self):

        port_client_mapping = defaultdict(list)
        for c in self.config:
            client = self.try_create_zabbix_server_connection(c)
            if client is None:
                continue
            if client.check_is_connected():
                zabbix_id = str(c['docker_server_port'])
                port_client_mapping[zabbix_id].append(client)
        return port_client_mapping

    @staticmethod
    def try_create_zabbix_server_connection(c):
        try:
            client = ZabbixClient(
                ip=c['docker_server_ip'],
                port=c['docker_server_port'],
                username=ZABBIX_SERVER_USERNAME,
                password=ZABBIX_SERVER_PASSWORD
            )
            return client
        except Exception as e:
            ll.get_logger().error(f'Create zabbix server connection error: {e}')
            return None

    def add_snmp_host(self, ip, zabbix_server_id, snmp_community):
        """

        Args:
            ip:
            zabbix_server_id:
            snmp_community:

        Returns: 10606

        """
        clients = self.port_client_mapping.get(str(zabbix_server_id), None)
        if clients is None:
            ll.get_logger().error(f'Failed to get zabbix server client, zabbix_server_id: {zabbix_server_id}')
            return
        for client in clients:
            t = client.get_template('group', 'get_groups')
            t['params']['filter']['name'] = 'Discovered hosts'
            group_id = client.fetch(t)[0]['groupid']
            t = client.get_template('template', 'get')
            t['params']['filter']['name'] = 'Network Generic Device by SNMP'
            template_id = client.fetch(t)[0]['templateid']
            t = client.get_template('host', 'create_snmp')
            t['params']['groups'][0]['groupid'] = group_id
            t['params']['host'] = ip
            t['params']['interfaces'][0]['ip'] = ip
            t['params']['interfaces'][0]['details']['community'] = snmp_community
            t['params']['templates'][0]['templateid'] = template_id
            client.insert(t)

    def get_all_hosts(self):
        hst_lst = []
        for p, clients in self.port_client_mapping.items():
            for client in clients:
                t = client.get_template('host', 'get')
                hosts = client.fetch(t)
                hst_lst.extend(hosts)
        mapping = {}
        for h in hst_lst:
            mapping[h['host']] = h
        return mapping

    def delete_all_hosts(self):
        """
        delete all hosts
        Returns:

        """
        for p, clients in self.port_client_mapping.items():
            for client in clients:
                t = client.get_template('host', 'get')
                hosts = client.fetch(t)
                hosts_lst = []
                for host in hosts:
                    if host['name'] == 'Zabbix server':
                        continue
                    host_id = host['hostid']
                    hosts_lst.append(host_id)
                t = client.get_template('host', 'delete')
                t['params'] = hosts_lst
                client.insert(t)
